import React from 'react';
import { SideBar, Card, Image, Tag, Empty } from 'antd-mobile';
import { history } from 'umi';
import styles from './index.less';
import { courseAPI, categoryAPI, CourseLevel, CourseLevelLabel } from '@/services/api';

const Course: React.FC = () => {
    const [courses, setCourses] = React.useState<any[]>([]);
    const [categories, setCategories] = React.useState<any[]>([]);
    const [activeKey, setActiveKey] = React.useState('all');
    const baseUrl = 'http://localhost:3001';

    // 获取分类列表
    React.useEffect(() => {
        const fetchCategories = async () => {
            try {
                const res = await categoryAPI.getCategories();
                if (res.code === 200) {
                    setCategories(res.data);
                }
            } catch (error) {
                console.error('Failed to fetch categories:', error);
            }
        };

        fetchCategories();
    }, []);

    // 获取课程列表
    React.useEffect(() => {
        const fetchCourses = async () => {
            try {
                const categoryId = activeKey === 'all' ? undefined : Number(activeKey);
                const res = await courseAPI.getCourses(categoryId);
                if (res.code === 200) {
                    const formattedCourses = res.data.map(course => ({
                        ...course,
                        image: `${baseUrl}${course.image_url}`,
                    }));
                    setCourses(formattedCourses);
                } else {
                    // 如果请求失败，设置空数组
                    setCourses([]);
                }
            } catch (error) {
                console.error('Failed to fetch courses:', error);
                // 发生错误时也设置空数组
                setCourses([]);
            }
        };

        fetchCourses();
    }, [activeKey]);

    const getLevelText = (level: CourseLevel) => {
        return CourseLevelLabel[level] || '未知';
    };

    // 构建侧边栏项目
    const sidebarItems = React.useMemo(() => {
        return [
            { key: 'all', title: '全部' },
            ...categories.map(category => ({
                key: String(category.id),
                title: `${category.name}(${category.course_count || 0})`
            }))
        ];
    }, [categories]);

    return (
        <div className={styles.courseContainer}>            
            <div className={styles.sidebarWrapper}>
                <SideBar style={{backgroundColor: '#fff'}} activeKey={activeKey} onChange={setActiveKey}>
                    {sidebarItems.map(item => (
                        <SideBar.Item key={item.key} title={item.title} />
                    ))}
                </SideBar>
            </div>
            <div className={styles.courseContent}>
                <div className={styles.courseList}>
                    {courses.length > 0 ? (
                        courses.map(course => (
                            <Card 
                                key={course.id} 
                                className={styles.courseCard}
                                onClick={() => history.push(`/course-detail/${course.id}`)}
                            >
                                <Image
                                    src={course.image}
                                    className={styles.courseImage}
                                />
                                <div className={styles.courseInfo}>
                                    <Tag color='#ff4d4f' className={styles.hotTag}>
                                        {course.tags[0]}
                                    </Tag>
                                    <h4>{course.title}</h4>
                                    <Tag color='#1677ff' className={styles.levelTag}>
                                        {getLevelText(course.level)}
                                    </Tag>
                                    <div className={styles.footer}>
                                        <span className={styles.price}>¥{course.price}</span>
                                        <span className={styles.students}>
                                            {course.enrolled_students}人已报名
                                        </span>
                                    </div>
                                </div>
                            </Card>
                        ))
                    ) : (
                        <div className={styles.emptyWrapper}>
                            <Empty description='暂无课程' />
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default Course; 